package cn.dnui_xcz826.dnuifood_16110100826.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.List;

import cn.dnui_xcz826.dnuifood_16110100826.R;
import cn.dnui_xcz826.dnuifood_16110100826.controller.SearchResultActivity;
import cn.dnui_xcz826.dnuifood_16110100826.db.RecordDBOperation;
import cn.dnui_xcz826.dnuifood_16110100826.db.RecordSQLiteOpenHelper;

public class Fragment2 extends BaseFragment {
    private RecordDBOperation recordDBOperation;
    private RecordSQLiteOpenHelper helper;
    private Button searchBtn;
    private EditText editText;
    private TextView tv_clear,tv_tip;
    private HistoryListView listView;
    //private Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //context=getActivity();
        view=inflater.inflate(R.layout.activity_fragment2, container, false);
        //Toast.makeText(context, "fragment2", Toast.LENGTH_SHORT).show();
        helper=new RecordSQLiteOpenHelper(context);
        recordDBOperation=new RecordDBOperation(helper);
        initViews();
        initEvents();
        return view;
    }
    @Override//生命周期方法，View创建完成
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        helper=new RecordSQLiteOpenHelper(context);
        recordDBOperation=new RecordDBOperation(helper);
    }

    @Override
    public void onStop() {
        super.onStop();
        recordDBOperation.closedb();
    }

    void initViews(){
        editText=view.findViewById(R.id.editText);
        searchBtn=view.findViewById(R.id.searchBtn);
        tv_clear=view.findViewById(R.id.tv_clear);
        tv_tip=view.findViewById(R.id.tv_tip);
        listView=view.findViewById(R.id.listView);
    }

    void initEvents(){
        // 清空搜索历史
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordDBOperation.deleteData();
                showData("");
            }
        });

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recordDBOperation.insertData(editText.getText().toString().trim());
                showDetailInfo(editText.getText().toString().trim());
            }
        });
        // 搜索框的键盘搜索键点击回调
        editText.setOnKeyListener(new View.OnKeyListener() {
            // 输入完后按键盘上的搜索键
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() ==
                        KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager)
                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getActivity().getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = recordDBOperation.hasData(editText.getText().toString().trim());
                    if (!hasData) {
                        recordDBOperation.insertData(editText.getText().toString().trim());
                        showData("");
                    }
                    // 根据输入的内容模糊查询商品，并跳转到另一个界面
                    showDetailInfo(editText.getText().toString().trim());
                }
                return false;
            }
        });
        // 搜索框的文本变化实时监听
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                editText.setVisibility(View.VISIBLE);
                if (s.toString().trim().length() == 0) {
                    tv_tip.setText("搜索历史");
                } else {
                    tv_tip.setText("搜索结果");
                }
                String tempName = editText.getText().toString();
                showData(tempName);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                editText.setText(name);
                showDetailInfo(name);
            }
        });

    }

    @Override
    void initData() {

    }

    void showData(String tempName) {
        List list = recordDBOperation.queryData(tempName);
        // 创建 adapter 适配器对象
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), list, android.R.layout.simple_list_item_1, new String[]{"name"}, new int[]{android.R.id.text1});
        //listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    void showDetailInfo(String name) {
        //跳转到搜索结果处理页面
        Intent intent = new Intent(context, SearchResultActivity.class);
        intent.putExtra("search",name);
        context.startActivity(intent);
    }
}
